package com.songlanyun.modules.chain.job;

import com.songlanyun.config.ChainProperties;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.chain.service.ChainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 初始化未绑定区块链地址的会员账户
 * @author zhangqh
 */
@Component
@Slf4j
public class ChainSyncAccountAddress {

    @Resource
    ChainService chainService;

    @Resource
    AccountService accountService;

    @Resource
    ChainProperties chainProperties;

    // 每批次处理用户数
    private static final int MAX_PER_COUNT = 300;

    /**
     * 每 30s 处理未生成账户地址的账户重新生成
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void resend() {
        if (!chainProperties.getSyncAccountAddressJobEnabled()) {
            return;
        }

        List<AccountEntity> accountEntityList = accountService.getNullAccoutAddressUsers(MAX_PER_COUNT);
        accountEntityList.forEach(item -> {
            try {
                String accountAddress = chainService.createAccountAddress(item.getId());
                accountService.updateAccountAddress(item.getId(), accountAddress);
            } catch (Exception e) {
                log.error("初始化账户: {} 区块链地址异常：", item.getId(), e);
            }
        });
    }

}